<template>
  <div class="main-container">
    <div
      class="portal-tip"
      v-if="checkedTabbarIndex === 3"
    >
      <i class="el-icon-warning"></i>
      <span v-if="checkedTabbarIndex === 3"
        >{{ $t('portal.portalTip10') }}（{{ $t('portal.previewOnly') }}）</span
      >
    </div>
    <div class="portal-form-design" :style="{ height: styleHeight }">
      <mform-design
        :type-id="typeId"
        :mode="formDesignMode"
        :value="currentFields"
        :global-fields="globalFields"
        :index="checkedTabbarIndex"
        :filter-fields="filterFields"
        :is-open-register="isOpenRegister"
        :template-name="templateName"
        :theme-colour="themeColour"
        :language-list="languageList"
        @input="updateFields"
        ref="formDesignRef"
      >
      </mform-design>
    </div>
    <div class="portal-tabBar">
      <div
        class="portal-tabBar-item"
        :class="{
          active: checkedTabbarIndex === item.order,
        }"
        v-for="item in tabbarsList.filter(item => item.isVisible)"
        :key="item.title"
        @click="handleToggleTabbar(item.order)"
      >
        <i class="iconfont" :class="item.icon"></i>
        <span>{{ item.title }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, getCurrentInstance } from 'vue';
import { usePortal } from '@hooks/portal/useConfig.ts';
import { useIMSetting } from '@hooks/setting/useIMSetting.ts';
import { getDoorTypeFieldList } from '@src/api/PortalApi.ts';
import Platform from '@src/util/platform.ts';
import { getConfig } from '@src/api/ProductV2Api';
import { PortalTabbarEnum } from '@model/types/PortalConfig';
import i18n from '@src/locales';
/* mixin */
import { VersionControlIMMixin } from '@src/mixins/versionControlMixin';

export default {
  mixins: [VersionControlIMMixin],
  props: {
    tenantId: {
      type: String,
      default: '',
    },
    typeId: {
      type: String,
      default: '',
    },
    templateName: {
      type: String,
      default: '',
    },
    themeColour: {
      type: String,
      default: '',
    },
    languageList: {
      type: Array,
      default: () => [],
    },
    needServerDeleFiles: {
      type: Array,
      default: () => [],
    },
  },
  emits: ['updateState'],
  setup(props, { emit }) {
   
    const instance = getCurrentInstance();
    const formDesignRef = ref(null);
    const [IMSetting, IMEnabled] = useIMSetting();
    const isOpenRegister = ref(false);

    const {
      globalFields,
      tabbarsList,
      currentFields,
      checkedTabbarIndex,
      initDoorTypeField,
      updateFields,
      validateFields,
      buildFields,
      handleSave,
      handleCheckSave,
      handleBack,
      handleToggleTabbar,
    } = usePortal(formDesignRef);
    const filterFields = ref([]);

    const formDesignMode = computed(() => (IMEnabled.value ? 'door' : 'base'));

    const styleHeight = computed(() => {
      if (
        [PortalTabbarEnum.Home,PortalTabbarEnum.Service,PortalTabbarEnum.User].includes(checkedTabbarIndex.value)
      ) {
        return 'calc(100% - 44px)';
      }
      return 'calc(100% - 84px)';
    });

    const fetchFieldList = async () => {
      // this.loading = true;
      try {
        const { code, data, msg } = await getDoorTypeFieldList({
          tenantId: props.tenantId,
          typeId: props.typeId,
          draft: 1,
        });

        if (code !== '200')
          return Platform.notification({
            title: i18n.t('portal.portalTip14'),
            type: 'error',
            message: msg,
          });
        let fields = data?.filter(v=>v.formType !='userCenter').filter(v => {
          
          // 在线客服字段控制
          if (v.formType == 'im') {
            return instance?.proxy?._isShowIMModule
          }
          
          return v
        })
        initDoorTypeField(fields);
        emit('updateState', false);

        // this.loading = false;
      } catch (error) {
        emit('updateState', false);
        console.error(error);
      }
    };

    const isOpenRegisterCheck = () => {
      getConfig({
        configCode: ['PRODUCT_REGISTRATION'],
      }).then(res => {
        if (res.errorCode === 0) {
          isOpenRegister.value = !!res?.data[0]?.isOpen;
          if (!isOpenRegister.value) {
            filterFields.value.push('productRegister');
          }
        }
      });
    };

    const save = (isRelease = false) => {
      if (!validateFields()) return;

      const params = {
        tenantId: props.tenantId,
        doorTypeFieldVOS: buildFields(props.typeId),
        typeId: props.typeId,
      };
      if (props.needServerDeleFiles.length) {
        params.deleteFiles = props.needServerDeleFiles;
      }
      return handleSave(isRelease, params);
    };

    onMounted(() => {
      fetchFieldList();
      isOpenRegisterCheck();
    });

    return {
      formDesignRef,
      formDesignMode,
      currentFields,
      globalFields,
      filterFields,
      isOpenRegister,
      checkedTabbarIndex,
      handleToggleTabbar,
      updateFields,
      tabbarsList,
      save,
      handleCheckSave,
      handleBack,
      styleHeight,
    };
  },
};
</script>

<style lang="scss" scoped>
@import '../index';

.main-container {
  width: 100%;
  height: calc(100vh - 50px);

  .portal-tip {
    @include box-setting(100%, 40px, #fffbe6, 4px);
    @include flex-setting(flex-start);
    @include font-setting(14px, 400, #595959, 22px);
    border: 1px solid #ffe58f;

    i {
      font-size: 16px;
      margin: 0 6px 0 20px;
      color: #faad14;
    }
  }

  .portal-form-design {
    // width: 100%;
    // height: calc(100% - 44px);
    background: #ebf0f4;

    // .form-design {
    //   padding-top: 12px;
    //   padding-left: 12px;
    // }
    .form-design-setting {
      width: 430px;
    }
    .form-setting-panel {
      padding: 0;
    }
  }

  .portal-tabBar {
    padding: 0 430px 0 220px;
    @include box-setting(100%, 44px, #ffffff);
    @include flex-setting();
    box-shadow: inset 0px 1px 0px 0px #f2f2f2;

    &-item {
      @include box-setting(96px, 100%, #ffffff);
      @include flex-setting();
      @include font-setting(14px, 400, #595959, 20px);
      cursor: pointer;

      i {
        font-size: 17px;
        margin-right: 5px;
      }
    }

    .active {
      background: $color-primary-light-6;
      color: #ffffff;
    }
  }
}
</style>
